<template>
  <div class="rebody">
  <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="70px" class="ruleForm" label-position="left">
    <div @click="callbackfun" class="callback">
      <i class="el-icon-arrow-left"></i>
      返回</div>
    <div class="registHeader">注册</div>

    <el-form-item label="头像上传" prop="">
      <el-upload
        class="avatar-uploader"
        :limit="1"
        :file-list="fileList"
        action="Fake Action"
        ref="avatarPhoto"
        :auto-upload="false"
        :http-request="httpRequst"
        :on-change="filechange"
        list-type="picture"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <i class="el-icon-plus avatar-uploader-icon" v-if="!fileList.length>0"></i>
      </el-upload>
<!--      <el-button type="primary" size="small" @click="submitUpload">上传</el-button>-->
    </el-form-item>
 <el-form-item  label="账号" prop='userName'>
   <el-input  v-model="ruleForm.userName" ></el-input>
 </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="确认密码" prop="checkPass">
    <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="角色" prop="role">
    <el-radio-group v-model="ruleForm.role">
    <el-radio  label="1" >企业</el-radio>
    <el-radio  label="2">学生</el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item label="地址" prop="address"  v-if="ruleForm.role==1">
    <el-input v-model="ruleForm.address"></el-input>
  </el-form-item>
    <el-form-item :label="ruleForm.role==1?'营业执照':'学生证'" prop="photo" >
      <el-upload
        class="avatar-uploader"
        action="Fake Action"
        :limit="1"
        ref="certificat"
        :file-list="certificatesUrlsList"
        :auto-upload="false"
        :http-request="certificatesUrlshttpRequst"
        :on-success="certificatesUrlsSuccess"
         :on-change="certificatesUrlschange"
         :on-remove="certificatesUrlsfuncRemove"
         list-type="picture"
        :before-upload="certificatesUrlsUpload">
        <i class="el-icon-plus avatar-uploader-icon"  v-show="!certificatesUrlsList.length>0"></i>
      </el-upload>
<!--       <el-button type="primary" size="small" @click="certificatesUrlsubmitUpload" v-show="!certificatesUrlsList.length>0">上传</el-button>-->
       <!-- <div>{{certificatesUrlsList}}</div> -->
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="iphone">
      <el-input v-model="ruleForm.iphone"></el-input>
    </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
    <el-button @click="resetForm('ruleForm')">重置</el-button>

  </el-form-item>
</el-form>
  </div>
</template>

<script>
  import axios from 'axios';
const qs=require('qs')
export default {
  name: 'register',
 data() {
      let checkAge = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('年龄不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
              callback();
          }
        }, 1000);
      };
      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      let validatePass2 = (rule, value, callback) => {
        console.log(this.ruleForm.pass)
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
     let eamil =(rule,value,callback) =>{
       let test = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
       if(!value){
         callback(new Error('请填写邮箱'))
       }else if(!test.test(value)){
         callback(new Error('请正确填写邮箱'))
       }else{
         callback()
       }
     }
     let iphone = (rule,value,callback) =>{
       let test  =/^(13[0-9]|15[0|1|3|6|7|8|9]|18[8|9])\d{8}$/
       console.log(value,123)
       if(!value){
         callback(new Error('请填写电话号码'))
       }else if(!test.test(value)){
         callback(new Error('请填写正确的电话号码'))
       }else{
         console.log(111)
         callback()
       }
     }
    let photo =(rule ,value,callback)=>{

      if(!this.certificatesUrlsList.length>0){
          callback(new Error(`请上传${this.ruleForm.role==1?'营业执照':'学生证'}`))
      }else{
        callback()
      }
    }

   return {
     fileList:[],
     certificatesUrlsList:[],
        ruleForm: {
          password: '',
          checkPass: '',
          age: '',
          message:''
        },
        imageUrl:'',
        rules: {
          userName:{
             required: true, message: '请填写账号', trigger: 'blur'
          },
          password: [
            { validator: validatePass, trigger: 'blur',required: true }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur', required: true}
          ],
          age: [
            { validator: checkAge, trigger: 'blur',required: true }
          ],
         role: [
            { required: true, message: '请选选择角色', trigger: 'change' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'blur' }
          ],
          address:[{
            required: true, message: '请填写地址', trigger: 'blur'
          }],
          photo:[{
            required: true, validator:photo, trigger: 'change'
          }],
          email:[{
            validator:eamil,trigger: 'blur',required:true
          }],
          iphone:[{
            validator:iphone,trigger:'blur',required:true
          }]
        }
      };
    },
    methods: {
      certificatesUrlsfuncRemove(){
        this.certificatesUrlsList = []
      },
      radiochangefunc(){},
      beforeUploadFunc(file){
        console.log(file,'图片上传前')
      },
      certificatesUrlsubmitUpload(){
        this.$refs.certificat.submit()
      },
      submitUpload(){
        console.log(1111)
      this.$refs.avatarPhoto.submit();
      },
      //证件图片改变
      certificatesUrlschange(file,fileList){
        console.log(file,'zhenjian')
        this.certificatesUrlsList = fileList
        this.certificatesUrlshttpRequst(file)
      },
    //图片改变
      filechange(file,fileList){
        console.log(file,fileList,6666669999)
        this.fileList = fileList
        this.$refs.avatarPhoto.submit(file);
      },
      // 证件图片上传
      certificatesUrlshttpRequst(item){
        let fileData = new FormData()
         console.log(item,'itme')
        fileData.append('file',item.raw)
        axios({
          url:'/api/file/upload',
          headers:{
            'content-type': 'multipart/form-data'
          },
          method:"POST",
          data:fileData
        }).then(res=>{
          this.ruleForm.certificatesUrls = res.data.url
          console.log(this.ruleForm,'证件上传')
        })
      },
          // 图片上传
      httpRequst(item){
        console.log('parmas',this.fileList,item)
        let fileData = new FormData()
        fileData.append('file',item.raw)
        axios({
          url:'/api/file/upload',
          headers:{
            'content-type': 'multipart/form-data'
          },
          method:"POST",
          data:fileData
        }).then(res=>{
          console.log(res,999)
          this.ruleForm.avatarUrl = res.data.url
          console.log(this.ruleForm,'头像上传')
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // alert('submit!');
            console.log(this.ruleForm,'submit!')
            this.$ajax({
              url:'/registered',
              method: 'POST',
              headers:{
                'Content-Type': 'application/json',
              },
              data:{
                ...this.ruleForm
              }
            }).then(res=>{
              console.log(res,1111)
              if(res.code==200){
                this.$message.success(`注册成功,请重新登录`)
                setTimeout(()=>{
                  this.$router.push({
                    name:'login'
                  })
                },2000)
              }

            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.fileList = []
        this.$refs[formName].resetFields();
      },
      callbackfun(){
        this.$router.push('/login')
      },
      handleAvatarSuccess(){
        console.log('handleAvatarSuccess')
      },
      //证件
      certificatesUrlsSuccess(){
        console.log('certificatesUrlsSuccess')
      },
      //设置上传图片的格式头像
      beforeAvatarUpload(file){
        console.log('beforeAvatarUpload',file)
      },
      //设置上传图片的营业执照
      certificatesUrlsUpload(file){
        console.log('certificatesUrlsUpload',file)
      }
    }
  }

</script>

<style lang="less" scoped>
  .callback{
    color: deepskyblue;
    position: absolute;
    left: 5px;
    font-size: 14px;
  }
.rebody{
  width: 100%;
  height: 100%;
  background-color: #eee;
}
.registHeader{
/*position: relative;*/
/*left: 50%;*/
/*top: 0%;*/
/*  transform: translate(-50%);*/
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin: 0 auto
;
  font-size: 20px;
}
.ruleForm{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 40%;
  background-color: rgba(266, 266, 266, .5);
  border-radius: 10px;
  box-sizing: border-box;
  padding: 10px
;
}
</style>
